import { cloud } from '@hw-agconnect/cloud-server';
import { Student } from './Student'; // Post是Server Model


// default是Student对象类型使用的存储区名
const collection = cloud.database({ zoneName: 'default' }).collection(Student);

export class Studentobjectutils {
  //查询所有数据
  query() {
    return collection.query().get();
  }

  //更新云侧数据库
  // upsert(posts: Student[]) {
  //   return new Promise((resolve, reject) => {
  //     collection.upsert(posts.map(post => Student.parseFrom(post)))
  //       .then(result => resolve({ result }))
  //       .catch(err => reject(err))
  //   });
  // }
  //增加数据
  insert(value: Student) {
    return new Promise((resolve, reject) => {
      collection.upsert(value)
        .then(result => resolve({ result }))
        .catch(err => reject(err))
    })
  }

  //删除数据
  delete(value: Student) {
    return new Promise((resolve, reject) => {
      collection.delete(value)
        .then(result => resolve({ result }))
        .catch(err => reject(err))
    })
  }


  //修改数据
  upsert(value: Student) {
    return new Promise((resolve, reject) => {
      collection.upsert(value)
        .then(result => resolve({ result }))
        .catch(err => reject(err))
    })
  }

  //根据名字查询数据
  queryByName(name: string) {
    return new Promise((resolve, reject) => {
      collection
        .query()
        .equalTo('stuName', name)//设置查询条件
        .limit(1) // 限制只查一条
        .get()
        .then(result => {
          if (result && result.length > 0) {
            resolve(result[0]); // 返回第一条数据
          } else {
            resolve(null); // 没有匹配数据
          }
        })
        .catch(err => reject(err));
    });
  }
}
